/**
 * Created by chenwenhao on 2017/1/14.
 * @description 此模块用作app全局自定义的pipe
 */
import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
import {DecodeuriPipe} from "@shared/pipes/decodeuri-pipe/decodeuri.pipe";

/**
 * @description 此pipe用作angular safe html之用
 */
@Pipe({
  name: 'safeStyle'
})
export class SafeStyle implements PipeTransform {
  constructor(public sanitizer: DomSanitizer) {
    this.sanitizer = sanitizer;
  }

  transform(value) {
    return this.sanitizer.bypassSecurityTrustStyle(value);
  }

}

/**
 * @description 此pipe用作截取字符串之用
 * example {{value | truncate : 5}}
 */
@Pipe({
  name: 'truncate'
})
export class TruncatePipe {
  transform(value: string, args: number) {
    if (!value) {
      return '';
    }

    let limit = args > 0 ? args : 10;
    return value.length > limit ? value.substring(0, limit) + '...' : value;
  }
}

/**
 * @description 将数字格式周几转换成中文格式
 */
@Pipe({
  name: 'chineseDay'
})
export class ChineseDay implements PipeTransform {
  transform(value: number, args: string[]): string {
    const days: Array<string> = ['日', '一', '二', '三', '四', '五', '六'];
    return '日一二三四五六'[value];
  }
}

/**
 * @description 讲英文周几转换成中文格式
 */
@Pipe({
  name: 'ChineseWeek'
})
export class ChineseWeek implements PipeTransform {
  transform(value): string {
    const date = new Date(value);
    const numberDay = date.getDay();
    return '日一二三四五六'[numberDay];
  }
}

/**
 * @description 将时间戳转化为年月日，星期，十分
 * @author zhoukf-1349
 * @param value:string
 */
@Pipe({
  name: 'dateChange'
})
export class dateChange implements PipeTransform {
  transform(time: any): string {
    const date = new Date(time),
      month = date.getMonth(),
      getDate = date.getDate();
    const numberDay = date.getDay();
    const Y = date.getFullYear() + '.';
    const M = (month + 1 < 10 ? '0' + (month + 1) : month + 1) + '.';
    const D = getDate < 10 ? '0' + (getDate) : getDate + ' ';
    const T = '周' +  '日一二三四五六'[numberDay];
    const H = date.getHours();
    const MM = date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes();
    return Y + M + D + '  ' + T + ' ' + H + ':' + MM;
  }
}

/**
 * 适用将字符串数字周转换成中文格式
 */
@Pipe({
  name: 'recruitWeek'
})
export class recruitWeek implements PipeTransform {
  transform(value: string, args: string[]): string {
    if (value != null) {
      const valueArr = value.split(','),
        days = '日一二三四五六',
        length = valueArr.length;
      if (length > 1) {
        for (let i = 1; i < length; i++) {
          valueArr[i] = days[valueArr[i]];
        }
        return '周' + valueArr.join(',');
      } else {
        return '周' + days[valueArr[0]];
      }

    } else {
      return '时间待定';
    }

  }
}

/**
 * 适用将时间戳转成年月日
 */
@Pipe({
  name: 'changetime'
})
export class changetime implements PipeTransform {
  transform(time: any): string {
    if (typeof (time) !== 'undefined') {
      const date = new Date(time),
        month = date.getMonth(),
        getDate = date.getDate();
      const Y = date.getFullYear() + '-';
      const M = (month + 1 < 10 ? '0' + (month + 1) : month + 1) + '-';
      const D = getDate < 10 ? '0' + (getDate) : getDate + ' ';
      return Y + M + D;
    } else {
      return '时间待定';
    }

  }
}

/**
 * @description 将赛制id转换成赛制类型文字（描述的内容和代码实现的不一致）
 * example {{5001 | expense : 11人制度}}
 */
@Pipe({
  name: 'Distance'
})
export class Distance implements PipeTransform {
  transform(value: number): string {
    if (value > 1000) {
      return (value / 1000).toFixed(1) + 'km';
    }
    return value.toFixed(1) + 'm';
  }
}

@Pipe({
  name: 'Price'
})
export class Price implements PipeTransform {
  transform(value: string): number {
    return value && (parseInt(value, 10) / 100) || 0;
  }
}

/**
 * 适用将价格转成小数点后两位格式
 */
@Pipe({
  name: 'twoDotPrice'
})
export class twoDotPrice implements PipeTransform {
  transform(value: number): number | string {
    if (value === 0) {
      return '0.00';
    } else {
      return (value / 100).toFixed(2);
    }
  }
}

/**
 * 适用将价格取整数部分，如9.9，取9
 */
@Pipe({
  name: 'intPrice'
})
export class intPrice implements PipeTransform {
  transform(value: number): number | string {

    // if (value === 0) {
    //   return 0;
    // } else {
    //   return Math.floor(value / 100);
    // }
    return (value / 100) | 0;
  }
}

/**
 * 适用将价格取小数部分，如8.91，取91
 */
@Pipe({
  name: 'decimalPrice'
})
export class decimalPrice implements PipeTransform {
  transform(value: number): number | string {
    if (value === 0) {
      return '00';
    } else {
      const newValue = (value / 100) + '';
      const valueArr = newValue.split('.');
      if (valueArr[1]) {
        if (parseInt(valueArr[1], 10) < 10 && valueArr[1].length === 1) {
          return valueArr[1] + '0';
        } else {
          return valueArr[1];
        }

      } else {
        return '00';
      }
    }
  }
}

/**
 * @description 将数字转换成金额形式
 * @author ouyqx-691
 * @param value:数字
 * @param format：格式（整数（integer）：100->100,小数（decimal）100->100.00）
 */
@Pipe({
  name: 'money'
})
export class Money implements PipeTransform {
  transform(value: number): number | string {
    // let price;
    // if (value === 0) {
    //   return price = '免费';
    // } else {
    //   price = (value / 100).toFixed(2);
    //   const decimal = price.toString().split('.'); // 有没有小数
    //   if (!decimal[1]) { // 整数
    //     return price + '.00';
    //   } else { // 小数
    //     return decimal[0] + '.' + decimal[1];
    //   }
    // }
    if (value === 0) {
      return '免费';
    }
    return (value / 100).toFixed(2);
  }
}

@Pipe({
  name: 'zeroMoney'
})
export class zeroMoney implements PipeTransform {
  transform(value: number): number | string {
    if (value === 0) {
      return '0';
    }
    return (value / 100).toFixed(2);
  }
}



/**
 * @desc 整数数字转汉字
 */
@Pipe({
  name: 'chineseNumber'
})
export class ChineseNumber implements PipeTransform {
  transform(value: number): string {
    // const ary0 = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    const ary0 = "零一二三四五六七八九";
    const ary1 = ["", "十", "百", "千"];
    const ary2 = ["", "万", "亿", "兆"];
    const numberArr = value.toString();
    let ary = [];
    let zero = "";
    let newary = "";
    let i4 = -1;
    // for (let j = numberArr.length - 1; j >= 0; j--) {
    //   ary.push(numberArr[j]);
    // } // 倒转字符串。
    ary = numberArr.split('').reverse();
    const aryLength = ary.length;
    for (let i = 0; i < aryLength; i++) {
      if (i % 4 === 0) { // 首先判断万级单位，每隔四个字符就让万级单位数组索引号递增
        i4++;
        newary = ary2[i4] + newary;  // 将万级单位存入该字符的读法中去，它肯定是放在当前字符读法的末尾，所以首先将它叠加入$r中，
        zero = "";  // 在万级单位位置的“0”肯定是不用的读的，所以设置零的读法为空

      }
      // 关于0的处理与判断。
      if (ary[i] === '0') {  // 如果读出的字符是“0”，执行如下判断这个“0”是否读作“零”
        switch (i % 4) {
          case 0:
            break;
          // 如果位置索引能被4整除，表示它所处位置是万级单位位置，这个位置的0的读法在前面就已经设置好了，所以这里直接跳过
          case 1:
          case 2:
          case 3:
            if (ary[i - 1] !== '0') {
              zero = "零";
            }
            // 如果不被4整除，那么都执行这段判断代码：如果它的下一位数字（针对当前字符串来说是上一个字符，因为之前执行了反转）也是0，那么跳过，否则读作“零”
            break;

        }

        newary = zero + newary;
        zero = '';
      } else {  // 如果不是“0”
        newary = ary0[parseInt(ary[i], 10)] + ary1[i % 4] + newary;
        // 就将该当字符转换成数值型,并作为数组ary0的索引号,以得到与之对应的中文读法，其后再跟上它的的一级单位
        // （空、十、百还是千）最后再加上前面已存入的读法内容。
      }

    }
    if (newary.indexOf("零") === 0) {
      newary = newary.substr(1);
    } // 处理前面的0
    if (newary[1] === '十' && newary[0] === '一') {
      newary = newary.slice(1);
    }
    return newary;
  }
}

/**
 * @description 取绝对值
 * @author ouyqx-691
 * @param value 传入的数值
 */
@Pipe({
  name: 'abs'
})
export class abs implements PipeTransform {
  transform(value: any): any {
    // return Math.abs(value);
    value = +value;
    return value < 0 ? -value : value;
  }
}

/**
 * @description 数字转字母
 * @author ouyqx-691
 * @param value 传入的数值
 */
@Pipe({
  name: 'letter'
})
export class letter implements PipeTransform {
  transform(value: any): any {
    // const letters: Array<string> = [];
    // for (let i = 0; i < 26; i++) {
    //   letters.push(String.fromCharCode((65 + i)));
    // }
    // if (value < 26) {
    //   return letters[value];
    // } else {
    //   const multiple = Math.floor(value / 26);
    //   const firstLetter = letters[multiple - 1];
    //   const secondLetter = letters[value % 26 + multiple];
    //   return firstLetter + secondLetter;
    // }
    if (value < 26) {
      return String.fromCharCode(65 + value);
    }
    const firstLetter = String.fromCharCode(65 + (value / 26 | 0) - 1);
    const secondLetter = String.fromCharCode(65 + value % 26);
    return firstLetter + secondLetter;
  }
}

/**
 * @description 时间倒计时，大于一天显示天数，小于一天，显示时分
 * @author baoww765
 * @param value 传入的数值
 */
@Pipe({
  name: 'remainingTimePipe'
})
export class RemainingTimePipe implements PipeTransform {
  transform(time: any) {
    if (typeof (time) !== 'undefined') {
      const days = time / (60 * 60 * 24 * 1000);
      const hours = time / (60 * 60 * 1000);
      if (days > 100) {
        return '99+天';
      } else if (days > 1) {
        return Math.floor(days) + '天';
      } else if (hours >= 1) {
        const minutes = (hours - Math.floor(hours)) * 60;
        return (Math.floor(hours) >= 10 ? Math.floor(hours) : ('0' + Math.floor(hours))) +
          ':' + (Math.floor(minutes) >= 10 ? Math.floor(minutes) : ('0' + Math.floor(minutes)));
      } else if (hours > 0) {
        return '00:' + (Math.floor(hours * 60) >= 10 ? Math.floor(hours * 60) : '0' + Math.floor(hours * 60));
      } else if (time === 0) {
        return '00:00';
      }
    }
    /*  需要修改的，但是无法测试，众筹页面
if (time !== void 0) {
  const minutes = time / 60000 | 0;
  const hours = minutes / 60 | 0;
  const days = hours / 24 | 0;
  if (days > 1) {
    return days > 99 ? '99+天'：days + '天';
  }
  if (hours < 10) {
    hours = '0' + hours;
  }
  minutes = minutes - hours * 60;
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  return hours + ':' + minutes;
}*/
  }
}


/**
 * @description 发布时间，tiem < 24小时：显示时分; 3天> time >1天：显示天数; tiem > 3天：显示年月日;
 * @author zhupw1360
 * @param value 传入的数值
 */
@Pipe({
  name: 'manageTimePipe'
})
export class ManageTimePipe implements PipeTransform {
  transform(time: any) {
    const nowTime = new Date().getTime();

    if (typeof (time) !== 'undefined') {
      const disTime = Math.abs(nowTime - time) / 1000;
      const days = Math.floor(disTime / (60 * 60 * 24));
      const hours = Math.floor(disTime / (60 * 60));
      const min = Math.floor(disTime / 60);

      if (days > 3) {
        const date = new Date(time);
        const Y = date.getFullYear() + '-';
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate() + ' ';
        return Y + M + D;
      } else if (days <= 3 && days >= 2) {
        return days + '天前';
      } else if (days < 2 && hours >= 24) {
        return '昨天';
      } else if (hours < 24 && hours >= 1) {
        return hours + '小时前';
      } else if (hours < 1) {
        return min + '分钟前';
      }

    }
  }

}

/**
 * @description 获取年龄
 * @author ouyqx-691
 * @param value 传入的时间戳
 */
@Pipe({
  name: 'age'
})
export class Age implements PipeTransform {
  transform(timestamp: number): number {
    const curYear = new Date().getFullYear();
    const birthYear = new Date(timestamp).getFullYear();
    return curYear - birthYear;
  }
}

export const SHARED_PIPES = [
  SafeStyle,
  TruncatePipe,
  ChineseDay,
  ChineseWeek,
  ChineseNumber,
  recruitWeek,
  letter,
  abs,
  Money,
  decimalPrice,
  intPrice,
  twoDotPrice,
  Price,
  changetime,
  Distance,
  RemainingTimePipe,
  ManageTimePipe,
  DecodeuriPipe,
  Age,
  dateChange,
  zeroMoney
];
